<% if @dirs %>
  
  <% sel = @archive || @dirs.last %>
  
  <% @dirs.each do |dir| %>
    <% uid = dir[:path].blank? ? 'Kapow!' : dir[:path] %>
    <% title = File.basename(uid).strip %>
    <% slug = sluggify(uid) %>

    <ul id="<%= slug %>" title="<%=title%>"<%=' selected="true"' if sel==dir%>>
      <%# Show last read comic (from cookie) %>
      <% if @saved %>
        <li class="comic">
          <span>Currently reading:</span>
          <h4 onclick="comic(this,'<%=u(@saved[:book])%>',<%=@saved[:page]%>)">
            <%= File.basename(@saved[:book]) %>, page <%= @saved[:page] %>
          </h4>
        </li>
      <% end %>

      <%# List all directories at this level %>
      <% dir[:dirs].each do |d| %>
        <% path = dir[:path].blank? ? d : File.join(dir[:path], d) %>
        <li class="dir">
          <%= link_to(d, '/', :path => path) %>
        </li>
      <% end %>

      <%# List all archives at this level %>
      <% dir[:archives].each do |archive| %>
        <% path = dir[:path].blank? ? archive : File.join(dir[:path], archive)%>
        <li class="archive"> 
          <%= link_to(archive, '/comic', :path => path) %>
        </li>
      <% end %>
    </ul>
    <% unless sel==dir %>
      <script>
        window.iui.kapow = window.iui.kapow || [];
        window.iui.kapow.lastPage = window.iui.kapow.existingPage || null;
        window.iui.kapow.existingPage = document.getElementById('<%= slug %>');
        window.iui.addToHistory(
          window.iui.kapow.existingPage, 
          window.iui.kapow.lastPage
        );
      </script>
    <% end %>
  <% end %>

<% end %>

<% if @archive %>
  <% if @page.found? %>
    <% uid = @archive.name %>
    <% title = File.basename(uid).strip %>
    <% slug = sluggify(uid) %>
    <% a_path = u(@path) %>
    <ul id="<%= slug %>" title="<%= title %>" selected="true">
      <li class="comic">
        <h4 onclick="comic(this, '<%= a_path %>', 0)">
          <img src="<%= @page.public_filename %>" style="width: 50px" />
          <%= title %>
        </h4>
      </li>
      <% @filenames.each_with_index do |page, index| %>
        <li class="archive" onclick="comic(this,'<%= a_path %>', <%=index%>)">
          <%= page %>
        </li>
      <% end %>
    </ul>
  <% else %>
    <div>
      Sorry, this does not appear to be a valid comic. Extraction output:

      <% @archive.errors.each do |error| %>
        <pre>
          <% error %>
        </pre>
      <% end %>
    </div>
  <% end %>
<% end %>
